<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Hash;
use DB;
use Config;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class GoodController extends Controller
{
    public static function getAllCate(){

        return DB::table('cates')->get();
    }

    /**
     * 递归遍历数据
     */
    public static function getCateArr($cates,$pid){
        $data = [];
        foreach ($cates as $k=>$v){
            if($v->pid == $pid){
                $v->sub=self::getCateArr($cates,$v->id);
                $data[] =$v;
            }
        }
        return $data;
    }

    /**
     * 递归查询所有分类
     */

    public function getCatesByPid($pid){

        $res = DB::table('cates')->where('pid',$pid)->get();
        $data = [];
        foreach ($res as $key => $value) {
            $value->sub = $this->getCatesByPid($value->id);
            $data[]=$value;
        }
        return $res;

    }

    /**
     * 查询所有分类下的子分类 按照sql排序
     *
     * select *,concat(path,",",id) as paths form cates order by paths;
     */
    public static function getCates(){
        $res = DB::table('cates')
        ->select(DB::raw('*,concat(path,",",id) as paths'))
        ->orderBy('paths')
        ->get();
        foreach($res as $k=>$v){
            $tmp = explode(',',$v->path);
            $len = count($tmp)-1;
            //修改分类的名称
            $res[$k]->catename = str_repeat('|----',$len).$v->catename;
        }
        // dd($res);
        return $res;
    }

    // 商品  添加页面
    public function getAdd()
    {
        // 显示模板
        $all = $this->getAllCate();

        $res = $this ->getCateArr($all,0);
        
        $cates = self::getCates();

    
        return view('good.add',['cates'=>$cates]);
    }


    // 商品数据的插入操作
    public function postInsert(Request $request){
        // dd($request->all());

        $this->validate($request, [
                'proname' => 'required',
                'cateid' => 'required',
                'price' => 'required',
                'image' => 'required',
                'store' => 'required',
                'des' => 'required',
                'state' => 'required',
            ],[
                'proname.required' => '商品名不能为空',
                'cateid.required' => '商品类别不能为空',
                'price.required' => '商品价格不能为空',
                'image.required' => '商品图片不能为空',
                'store.required' => '商品库存量不能为空',
                'des.required' => '商品描述不能为空',
                'state.required' => '商品状态不能为空',
            ]);

        // dd($request->all());
        // 拼接数据

        $data = $request->except(['_token']);
        $data['addtime'] = date("Y-m-d H:i:s",time());
        // $data['cateid'] = 12;

        // 调用方法进行图片上传
        $res = self::upload($request,'image');
        $data['image'] = $res['image'];
        
        //执行数据插入
        $res = DB::table('goods')->insert($data);
        if($res){
            return redirect('admin/good/index')->with('success','数据添加成功');
        }else{
            return back()->with('error','数据插入失败');
        }
    }
    // 分类首页
    public  function getIndex(Request $request)
    {
        // 读取数据 并且分页
         $goods=DB::table('goods')
         ->where(function($query)use($request){
            $query->where('proname','like','%'.$request->input('keywords').'%');
        })
        ->paginate($request->input('num',10));
        
        //解析模板
        return view('good.index',['goods'=>$goods,'request'=>$request->all()]);  
    }


    // 商品修改
    public function getEdit($id){
        // 查询数据
        $res =  DB::table('goods')->where('id',$id)->first();
        //显示模板 分配变量
        return view('good.edit',['goodinfo'=>$res]);
    }

    public function postUpdate(Request $request)
    {
        //接收数据
        $data=$request->only(['proname','price','store','state']);
        $id=$request->input('id');
        //执行修改
        $res=DB::table('goods')->where('id',$id)->update($data);
        if($res){
            //成功 页面跳转到列表页
            return redirect('admin/good/index')->with('success','数据修改成功');
        }else{
            //失败 跳转到添加页
            return back()->with('error','数据修改失败');
        }
    }

    // 用户的数据删除
    // admin/user/delete  get
    public function getDelete($id){
        // 执行删除
        $res = DB::table('goods')->where('id',$id)->delete();
        if($res){
            //成功 页面跳转到列表页
            return redirect('admin/good/index')->with('success','数据删除成功');
        }else{
            //失败 跳转到添加页
            return back()->with('error','数据删除失败');
        }
    }

    // 图片上传
    public static function upload(Request $request,$file)
    {
        // 图片上传
        if($request->hasFile($file)){
            // 获取文件上传的后缀名
            $houzhuim = $request->file($file)->getClientOriginalExtension();
            $fileName = md5(time().rand(1,20)).'.'.$houzhuim;
            $request->file($file)->move(Config::get('app.upload_dir'),$fileName);
            $data[$file] = trim(Config::get('app.upload_dir').$fileName,'.');
            return $data;
        }
    }


    /**
     * 前台商品详情
     */

    public function show($id){
        // DB::table('users')
        //     ->join('contacts', 'users.id', '=', 'contacts.user_id')
        //     ->join('orders', 'users.id', '=', 'orders.user_id')
        //     ->select('users.id', 'contacts.phone', 'orders.price')
        //     ->get()
        $dif = DB::table('link')->get();
        $goods = DB::table('goods')
                ->join('cates','cates.id','=','goods.cateid')
                ->select('goods.*','cates.catename as names')
                // ->find($id);
                ->where('goods.id',$id)
                ->get();
        //读取当前分类商品
                // dd($goods->image);
                // dd($goods);

        // dd($id);
        $res = DB::table('goods')->where('id',$id)->first();
        // dd($res);
        $data['id'] = $res->id;
        $res1 = DB::table('evaluate')->where('goodsid',$data['id'])->get();
        // dd($res1);
        $data = [];
        foreach ($res1 as $k => $v){
            $tmp['des'] = $v->des;
            $tmp['userid'] = $v->userid;
            $res2 = DB::table('users')->where('id',$tmp['userid'])->first();
            $tmp['username'] = $res2->username;
            // dd($tmp);
            $data[] = $tmp;
        }
        // $data['des'] = $res1->des;
        // dd($data);
        return view('goods.detail',['goods'=>$goods,'data'=>$data,'lianjie'=>$dif]);
    }
}

